
var mongoClient = require('mongodb').MongoClient

var ObjectID = require('mongodb').ObjectID

var dbUrl = 'mongodb://127.0.0.1:27017' //数据库网址

var dbName = 'productList'


function __connectDb(callback) {

    mongoClient.connect(dbUrl,{ useNewUrlParser: true }, function (err, client) {

        if (err) {
            console.log('数据库连接失败')
            return
        }


        //增删改查操作
        callback(err, client)
    })
    
}

//暴露objectId
exports.ObjectID = ObjectID

//查询数据
exports.find = function (collectionName, json, callback) {

    __connectDb(function (connectErr, client) {
        var db = client.db(dbName)
        var result = db.collection(collectionName).find(json)
        result.toArray(function (ctrlErr, docs) {
            callback(ctrlErr, docs)
            client.close()
        })
    })

}

//插入数据
exports.insert = function (collectionName, json, callback) {

    __connectDb(function (connectErr, client) {

        var db = client.db(dbName)
        db.collection(collectionName).insertOne(json,function (ctrlErr, data) {
            callback(ctrlErr, data)
        })

    })

}

//增加数据
exports.update = function (collectionName, json1, json2, callback) {

    __connectDb(function (connectErr, client) {

        var db = client.db(dbName)
        db.collection(collectionName).updateOne(json1,{$set:json2},function (ctrlErr, data) {
            callback(ctrlErr, data)
        })

    })
}

//删除数据
exports.deleteOne = function (collectionName, json, callback) {

    __connectDb(function (connectErr, client) {

        var db = client.db(dbName)
        db.collection(collectionName).deleteOne(json,function (ctrlErr, data) {
            callback(ctrlErr, data)
        })

    })
}
